package com.qdx.qiuzidao;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.sdk.android.push.popup.PopupNotifyClick;
import com.bytedance.ads.convert.BDConvert;
import com.bytedance.applog.AppLog;
import com.bytedance.applog.InitConfig;
import com.bytedance.applog.util.UriConstants;
import com.umeng.commonsdk.UMConfigure;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Objects;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "mainInit";
    private InitConfig config;
    private BinaryMessenger messenger;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        (new PopupNotifyClick((title, summary, extMap) -> {
        })).onCreate(this, this.getIntent());
        UMConfigure.preInit(this,"65642dc358a9eb5b0a118d7c", "Umeng");
        UMConfigure.setLogEnabled(false);
//        copyAssetsToPrivateDir(this);
        AliMessage.startEvents(Objects.requireNonNull(getFlutterEngine()));
        try {
            InputStream inputStream = getAssets().open("config.yaml");
            Yaml yaml = new Yaml();
            Map<String, Object> data = yaml.load(inputStream);
            // 可以使用data来访问YAML文件中的内容
            Map<String, Object> configMap = (Map<String, Object>) data.get("config");
            String channel = (String) configMap.get("channel");
            /* 初始化SDK开始 */
            // 第一个参数APPID: 参考2.1节获取
            // 第二个参数CHANNEL: 填写渠道信息，请注意不能为空
            assert channel != null;
            config = new InitConfig("579786", channel);
            // 设置数据上送地址
            config.setUriConfig(UriConstants.DEFAULT);
            config.setImeiEnable(false);//建议关停获取IMEI（出于合规考虑）
            config.setAutoTrackEnabled(true); // 全埋点开关，true开启，false关闭
            config.setLogEnable(true); // true:开启日志，参考4.3节设置logger，false:关闭日志
            AppLog.setEncryptAndCompress(true); // 加密开关，true开启，false关闭
            config.setEnablePlay(true); // 配置心跳事件（时长统计）
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        new MethodChannel(messenger, CHANNEL).invokeMethod("shutdown",null);
        super.onDestroy();
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        ClipBoardHook.hookClipBoard(flutterEngine);
        messenger = flutterEngine.getDartExecutor().getBinaryMessenger();
        MethodChannel methodChannel = new MethodChannel(messenger, CHANNEL);
        AliMessage.init(this, flutterEngine);
        methodChannel.setMethodCallHandler((call, result) -> {
            if (call.method.equals("initAds")) {
                BDConvert.getInstance().init(this);
                AppLog.init(this, config, this);
                /* 初始化SDK结束 */
                result.success("init done");
            } else if(call.method.equals("someMessage")){
                AliMessage.sendMessage( new Message(
                    "init",
                    "",
                    "",
                    "",
                    "",
                    "",
                    MessageType.JOIN_GROUP
                ));
            }else{
                result.notImplemented();
            }
        });
        super.configureFlutterEngine(flutterEngine);
    }

    public void copyAssetsToPrivateDir(Context context) {
        AssetManager assetManager = context.getAssets();
        String[] files = null;
        try {
            // 获取assets/gifts目录下的所有文件和子目录名
            files = assetManager.list("gifts");
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }
        if (files != null) {
            for (String filename : files) {
                InputStream in = null;
                OutputStream out = null;
                try {
                    // 打开assets中的文件输入流
                    in = assetManager.open("gifts/" + filename);
                    // 在私有目录中创建对应的文件输出流
                    File outFile = new File(context.getFilesDir(), filename);
                    out = new FileOutputStream(outFile);
                    copyFile(in, out);
                } catch(IOException e) {
                    Log.e("tag", "Failed to copy asset file: " + filename, e);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            Log.e("tag", "Failed to copy asset file: " + filename, e);
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            Log.e("tag", "Failed to copy asset file: " + filename, e);
                        }
                    }
                }
            }
        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }
}
